<?php

namespace App\Http\Controllers\Admin\Dispatch;

use App\Exports\MaterialExport;
use App\Exports\OfficeExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\dispatch\MaterialRequest;
use App\Imports\MaterialImport;
use App\Imports\OfficeImport;
use App\Models\administration\OfficeModel;
use App\Models\dispatch\MaterialModel;
use App\Models\dispatch\StockModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Material extends Controller
{
    use MaterialRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = MaterialModel::query()->with('create_admin');

        if($name){
            $query->where('name', 'like', '%'.$name.'%');
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'name' => $item->name,
                'code' => $item->code,
                'unit' => $item->unit,
                'spe' => $item->spe,
                'color' => $item->color,
                'limit' => $item->limit,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name : '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $find = MaterialModel::where('name', $params['name'])->first();
        if($find){
            return $this->error('物料已存在');
        }

        DB::beginTransaction();
        try {
            $model = new MaterialModel();
            $model->name = $params['name'];
            $model->unit = $params['unit'];
            $model->spe = $params['spe'];
            $model->color = $params['color'];
            $model->limit = $params['limit'];
            $model->code = getCode('material', 'WL');
            $model->created_admin_id = $auth->id;
            $model->save();

            $stock = new StockModel();
            $stock->material_id = $model->id;
//            $stock->month = date('Y-m', time());
            $stock->created_admin_id = $auth->id;
            $stock->save();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = MaterialModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        if($model->name != $params['name']){
            $find = MaterialModel::where('name', $params['name'])->first();
            if($find){
                return $this->error('物料已存在');
            }
        }

        $model->name = $params['name'];
        $model->unit = $params['unit'];
        $model->spe = $params['spe'];
        $model->color = $params['color'];
        $model->limit = $params['limit'];
        $model->save();

        return $this->success();
    }


    public function delete(int $id){
        $model = MaterialModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }


    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = MaterialModel::query();
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();


        $list = $items->map(function($item) {
            $res = [
                'name' => $item->name,
                'code' => $item->code,
                'unit' => $item->unit,
                'spe' => $item->spe,
                'color' => $item->color,
                'limit' => $item->limit,
            ];
            return $res;
        });

        $file_name = '物料-'.date('Ymd').'.xlsx';
        return Excel::download(new MaterialExport($list), $file_name);
    }

    public function import(Request $request)
    {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file){
            return $this->error('请选择文件');
        }

        $import = new MaterialImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $find = MaterialModel::where('name', $line['name'])->first();

                if($find){
                    DB::rollBack();
                    $this->error('物料【'. $line['name'] .'】已存在');
                }

                $model = new MaterialModel();
                $model->name = $line['name'];
                $model->code = $line['code'];
                $model->unit = $line['unit'];
                $model->spe = $line['spe'];
                $model->color = $line['color'];
                $model->limit = $line['limit'];
                $model->created_admin_id = $auth->id;
                $model->save();

                $stock = new StockModel();
                $stock->material_id = $model->id;
//            $stock->month = date('Y-m', time());
                $stock->created_admin_id = $auth->id;
                $stock->save();
                DB::commit();

            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }

}
